package com.javaweb.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


/**
 * @author HLQ
 * @date 2024/11/2 14:56
 */
@RestController
@Slf4j
@RequestMapping("/web")
public class WebObjectController {
    @GetMapping("/request")
    public String processRequest(HttpServletRequest req){
        log.info("url : {} \n, queryString : {}",req.getRequestURL(),req.getQueryString());
        //?
        log.info("user-agent:{}",req.getHeader("user_agent"));
        return  "ok";
    }

    @GetMapping("/session")
    public String processSession(HttpSession session){
        session.setAttribute("user","hlq");
        log.info("session : {}",session.getId());
        return "successful , session id : " +session.getId();
    }
    @GetMapping("/session/further")
    public String processSessionFurther(HttpSession session){
        log.info("get from session:{}",session.getAttribute("user"));
        log.info("session id: {}",session.getId());
        return "successful , session id : " +session.getId();
    }
    @GetMapping("cookie/add")
    public String processCookie(HttpServletResponse resp){
        Cookie cookie = new Cookie("user","hlq");
        cookie.setMaxAge(60*60*24);
        resp.addCookie(cookie);
        return "successful";
    }
    @GetMapping("cookie/get")
    public String processCookie(HttpServletRequest req){
        Cookie[] cookies = req.getCookies();
        for(Cookie cookie:cookies){
            log.info("get cookie name : {}, values : {}",cookie.getName(),cookie.getValue());
        }
        return "successful";
    }
    @GetMapping("cookie/subMit")
    public String processCookie(@RequestParam String submitValue, HttpServletResponse resp){
        Cookie cookie = new Cookie("user",submitValue);
        cookie.setMaxAge(60*60*24);
        resp.addCookie(cookie);
        log.info("cookie add successfully");
        return "successful";
    }
    public String returnCookie(HttpServletRequest req){
        Cookie[] cookies = req.getCookies();
        for(Cookie cookie:cookies){
            log.info("get cookie name : {}, values : {}",cookie.getName(),cookie.getValue());
        }
        return "successful";
    }
}
